using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using VegetableSale.NET.Entities;

namespace VegetableSale.NET.Controllers;

[Route("api/[action]")]
[ApiController]
public class HomeController : ControllerBase
{
    private readonly IWebHostEnvironment webHostEnvironment;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="webHostEnvironment"></param>
    public HomeController(IWebHostEnvironment webHostEnvironment)
    {
        this.webHostEnvironment = webHostEnvironment;
    }

    /// <summary>
    /// 接收文件
    /// </summary>
    /// <returns></returns>
    [HttpPost(Name = "goodupload")]
    public SysResult goodupload()
    {
        IFormFileCollection files = Request.Form.Files;
        string fileNameReturn = "";
        foreach (IFormFile file in files)
        {
            string directory = Path.Combine("/Users/litengyue/Projects/WebstormProjects/Vue-vegetablesale/static",
                "upload");
            string fileExtension = Path.GetExtension(file.FileName);
            string fileName = Guid.NewGuid().ToString() + fileExtension;
            string filePath = Path.Combine(directory, fileName);
            fileNameReturn = fileName;

            // 生成文件路径
            while (System.IO.File.Exists(filePath))
            {
                fileName = Guid.NewGuid().ToString() + fileExtension;
                filePath = Path.Combine(directory, fileName);
                fileNameReturn = fileName;
            }

            // 写入文件
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                file.CopyTo(stream);
                stream.Flush();
            }
        }

        return new SysResult(true, fileNameReturn);

        // return JsonConvert.SerializeObject(new
        // {
        //     code = 0,
        //     msg = "",
        //     data = fileNameReturn
        // });
    }
}